package project;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * 
 * @author Zaid Al-Ogaili
 * main class running the whole application
 * shows the logging in frame
 *
 */

public abstract class TLoginMain1 extends JFrame {
	DatabaseFeed df = new DatabaseFeed();
	public static final String MAIN_PANEL = "main";
	public static final String LOGIN_PANEL = "login";
	private static JPanel cards;
	private JPanel contentPane;
	private TLogin1 loginForm;
	static TLoginMain1 f;
	 

	public void setGui() {
		try {
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			setLocation(400, 300);
			cards = new JPanel(new CardLayout());
			setContentPane(cards);
			loginForm = new TLogin1(new Authenticator());
			contentPane = new JPanel();
			cards.add(loginForm, LOGIN_PANEL);
			cards.add(contentPane, MAIN_PANEL);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


//	public Container getContentPane() {
//		return contentPane;
//	}


	public static void main(String[] args) {
		try {
			SwingUtilities.invokeAndWait(new Runnable() {
				public void run() {
					f = new TLoginMain1() {

						public boolean allow(String username, String pw) {

							return df.userExists(username, pw);
							
						}

						
					};
					f.setGui();
//					f.getContentPane()
//					.add(new JLabel("Congratulations - you're logged in!"));
					f.pack();
					f.setVisible(true);
					
					}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public abstract boolean allow(String userName, String password);

	/**
	 * 
	 * @author Zaid Al-Ogaili
	 * action listener to check if the input data is correct
	 *
	 */
	private class Authenticator extends AbstractAction {

		public void actionPerformed(ActionEvent e) {
			if (allow(loginForm.getUserName(), loginForm.getPassword())) {
				TCategoriesAndFeeds me = new TCategoriesAndFeeds();
				CardLayout cl = (CardLayout) (cards.getLayout());
				cl.show(cards, MAIN_PANEL);
				me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				me.setVisible(true);
				
//TODO				remove(cards);
				f.setVisible(false);
				/*show warning message if input is incorrect */
			} else {
				JOptionPane.showMessageDialog(null, "Incorrect username or password!\n" +
						"Please, try again");
			}
		}
	}
}